package cn.opopopo.design_pattern_learn.行为型.iterator;

class BookShelf implements Iterable<Book> {
    private Book[] books;
    private int count = 0;

    public BookShelf(int maxSize) {
        this.books = new Book[maxSize];
    }

    public void addBook(Book book) {
        if (count < books.length) {
            books[count++] = book;
        }
    }

    public int getSize() {
        return count;
    }

    public Book getBookAt(int index) {
        return books[index];
    }

    // 实现 Iterable 接口
    @Override
    public Iterator<Book> createIterator() {
        return new BookShelfIterator();  // 返回内部迭代器
    }

    // 内部类：书架专用迭代器
    private class BookShelfIterator implements Iterator<Book> {
        private int currentIndex = 0;

        @Override
        public boolean hasNext() {
            return currentIndex < count;
        }

        @Override
        public Book next() {
            if (!hasNext()) {
                throw new java.util.NoSuchElementException();
            }
            return books[currentIndex++];  // 返回当前元素，指针后移
        }
    }
}